import React, { Component } from 'react'
import SQLiteStorage from 'react-native-sqlite-storage';

SQLiteStorage.DEBUG(true);
var db;
export default class SQLite extends Component {

    open() {
        db = SQLiteStorage.openDatabase(
            "wjsj.db",
            "1.0",
            "MySQLite",
            -1,
            () => {
                this._successCB('open');
            },
            (err) => {
                this._errorCB('open', err);
            });
        return db;
    }

    init() {
        if (!db) {
            this.open();
        }
        db.transaction((tx) => {
            tx.executeSql('CREATE TABLE IF NOT EXISTS USER(' +
                'id varchar )' 
                , [], () => {
                    this._successCB('executeSql');
                }, (err) => {
                    this._errorCB('executeSql', err);
                });
        }, (err) => {//所有的 transaction都应该有错误的回调方法，在方法里面打印异常信息，不然你可能不会知道哪里出错了。  
            this._errorCB('transaction', err);
        }, () => {
            this._successCB('transaction');
        })
    }
    //退出登录时，删除用户表中信息
    logOut() {
        if (!db) {
            this.open();
        }
        db.transaction((tx) => {
            tx.executeSql('delete from user', [], () => {
            });
        });
    }
    //用户登录时，将当前用户信息插入到user表中
    login(user) {
        if (!db) {
            this.open();
        }
        //this.init();
        this.logOut(); //清空表，保证只有当前用户 
        alert(JSON.stringify(user));
        db.transaction((tx) => {
            let id = user.id;//用户的id
            let sql = "INSERT INTO user(id)" +
                "values(?)";
            tx.executeSql(sql, [id], () => {
            }, (err) => {
                console.log(err);
            }
            );
        }, (error) => {
            this._errorCB('transaction', error);
        }, () => {
            this._successCB('transaction insert data');
        });
    }
    //关闭数据库
    close() {
        if (db) {
            this._successCB('close');
            db.close();
        } else {
            console.log("SQLiteStorage not open");
        }
        db = null;
    }


    _successCB(name) {
        console.log("SQLiteStorage " + name + " success");
    }
    _errorCB(name, err) {
        console.log("SQLiteStorage " + name);
        console.log(err);
    }
    render() {
        return null;
    }

}